
/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.jiujiudevice.web;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.boxin.ims.modules.jiujiudevice.entity.JiuDevice;
import com.boxin.ims.modules.jiujiudevice.entity.JiuSn;
import com.boxin.ims.modules.jiujiudevice.service.JiuDeviceService;
import com.boxin.ims.modules.jiujiudevice.service.JiuSnService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.RequestUtil;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * sn配置Controller
 * 
 * @author sxh
 * @version 2018-08-15
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH + "/jiujiudevice/jiuSn")
public class JiuSnController extends BaseController {

	@Autowired
	private JiuSnService jiuSnService;
	@Autowired
	private JiuDeviceService jiuDeviceService;

	@ModelAttribute
	public JiuSn get(@RequestParam(required = false) Long id) {
		if (id != null) {
			return jiuSnService.get(id);
		} else {
			return new JiuSn();
		}
	}

	@RequiresPermissions("jiujiudevice:jiuSn:view")
	@RequestMapping(value = { "list", "" })
	public String list(JiuSn jiuSn, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();

		Page<JiuSn> page = jiuSnService.find(new Page<JiuSn>(request, response), jiuSn);
		model.addAttribute("page", page);
		return "modules/jiujiudevice/jiuSnList";
	}

	@RequiresPermissions("jiujiudevice:jiuSn:view")
	@RequestMapping(value = "form")
	public String form(JiuSn jiuSn, Model model) {

		model.addAttribute("jiuSn", jiuSn);
		return "modules/jiujiudevice/jiuSnForm";
	}

	@RequiresPermissions("jiujiudevice:jiuSn:edit")
	@RequestMapping(value = "save")
	public String save(JiuSn jiuSn, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, jiuSn)) {
			return form(jiuSn, model);
		}
		JiuSn sn = jiuSnService.getBySn(jiuSn.getSn());
		if (sn != null && sn.getId() > 0) {
			addMessage(redirectAttributes, "保存sn配置'" + jiuSn.getSn() + "'失败,该设备sn已经存在！");
		} else {
			jiuSnService.save(jiuSn);
			addMessage(redirectAttributes, "保存sn配置'" + jiuSn.getSn() + "'成功");
		}
		return "redirect:" + Global.ADMIN_PATH + "/jiujiudevice/jiuSn/?repage";
	}

	@RequiresPermissions("jiujiudevice:jiuSn:edit")
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		jiuSnService.delete(id);
		//删除sn及相关的设备
		JiuSn jiuSn = jiuSnService.get(id);
		if(jiuSn != null){
			JiuDevice jiuDevice = jiuDeviceService.getBySn(jiuSn.getSn());
			jiuDeviceService.delete(jiuDevice.getId());
		}
		
		addMessage(redirectAttributes, "删除sn配置及相关设备成功");
		return "redirect:" + Global.ADMIN_PATH + "/jiujiudevice/jiuSn/?repage";
	}

	@ResponseBody
	@RequestMapping(value = "treeData")
	public String treeData(HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<JiuSn> list = jiuSnService.findAll();
		for (JiuSn s : list) {
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", s.getId());
			map.put("pId", 0);
			map.put("name", s.getSn());
			mapList.add(map);
		}
		return JsonMapper.getInstance().toJson(mapList);
	}

	@RequiresPermissions("jiujiudevice:jiuSn:edit")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);

			List<JiuSn> list = ei.getDataList(JiuSn.class);
			for (JiuSn sn : list) {
				if (StringUtils.isNotEmpty(sn.getSn())) {
					if (jiuSnService.saveNx(sn)) {
						successNum++;
					} else {
						failureNum++;
					}
					System.out.println(sn.getSn());
				} else {
				}
			}
			list = null;
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条SN，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条SN" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.ADMIN_PATH + "/jiujiudevice/jiuSn/?repage";
	}

	@RequiresPermissions("jiujiudevice:jiuSn:edit")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "SN导入模板.xlsx";
			List<JiuSn> list = Lists.newArrayList();
			JiuSn sn = new JiuSn();
			sn.setSn("869286037073272");
			list.add(sn);
			new ExportExcel("SN数据", JiuSn.class, 2).setDataList(list).write(response, fileName).dispose();
			list = null;
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.ADMIN_PATH + "/jiujiudevice/jiuSn/?repage";
	}

	@RequiresPermissions("jiujiudevice:jiuSn:edit")
	@RequestMapping(value = "export")
	public String export(JiuSn jiuSn, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "SN数据列表.xlsx";
			List<JiuSn> list = jiuSnService.find(jiuSn);
			new ExportExcel("SN数据", JiuSn.class, 2).setDataList(list).write(response, fileName).dispose();
			list = null;
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			addMessage(redirectAttributes, "导出SN数据失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.ADMIN_PATH + "/jiujiudevice/jiuSn/?repage";
	}

	// 公共方法根据url生成二维码图片后写入输出流里
	public static void getBarCodeImgByUrl(String url, OutputStream os) throws WriterException, IOException {
		// 二维码参数
		int width = 200; // 图像宽度
		int height = 200; // 图像高度
		String format = "png";// 图像类型
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		hints.put(EncodeHintType.MARGIN, 0);
		BitMatrix bitMatrix;
		bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);
		MatrixToImageWriter.writeToStream(bitMatrix, format, os);
	}

	// 入口
	@RequestMapping("download")
	public void download(HttpServletRequest request, HttpServletResponse response) {
		String sn = RequestUtil.getString(request, "sn");
		JiuSn j = jiuSnService.getBySn(sn);
		if (j != null && j.getId() > 0) {
			ZipOutputStream zos = null;
			try {
				String downloadFilename = j.getSn();// 文件的名称
				downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");// 转换中文否则可能会产生乱码
				response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
				response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename + ".zip");// 设置在下载框默认显示的文件名
				zos = new ZipOutputStream(response.getOutputStream());
				StringBuffer url = new StringBuffer();
				url.append(j.getSn());
				zos.putNextEntry(new ZipEntry(j.getSn()+".png"));// 命名
				getBarCodeImgByUrl(url.toString(), zos);// 拼接了url
				zos.flush();
				zos.close();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (WriterException e) {
				e.printStackTrace();
			} finally {
				if (zos != null) {
					try {
						zos.flush();
						zos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	// 批量下载二维码
	@RequestMapping("downAll")
	public void downAll(HttpServletRequest request, HttpServletResponse response) {
		List<JiuSn> list = jiuSnService.findAllSn();
		if (list != null && list.size() > 0) {
			ZipOutputStream zos = null;
			try {
					String downloadFilename = list.get(0).getSn();// 文件的名称
					downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");// 转换中文否则可能会产生乱码
					response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
					response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename + ".zip");// 设置在下载框默认显示的文件名
					zos = new ZipOutputStream(response.getOutputStream());
					for (int i = 0; i < list.size(); i++) {
					StringBuffer url = new StringBuffer();
					url.append(list.get(i).getSn());
					zos.putNextEntry(new ZipEntry(list.get(i).getSn()+ ".png"));// 命名
					getBarCodeImgByUrl(url.toString(), zos);// 拼接了url
				   }
				zos.flush();
				zos.close();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (WriterException e) {
				e.printStackTrace();
			} finally {
				if (zos != null) {
					try {
						zos.flush();
						zos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

}
